import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbgroup } from '../../../../atoms/db';
import Guid from '../../../../atoms/guid';

const logger = anylogger('pages/api/basicinformation/classgroup/update.api');

export type Result = {
	ok: boolean;
	message: string;
};

export type Message = ITbgroup;

/**
 * 课组管理-更新数据
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { group_id, ...body } = req.body as Message;
		//#region 验证必填
		// if (!body) {
		// 	res.status(200).json({
		// 		ok: false,
		// 		message: '课组编号不能为空！'
		// 	});
		// 	return;
		// }
		if (!body.groupname) {
			res.status(200).json({
				ok: false,
				message: '课组名称不能为空！'
			});
			return;
		}
		if (!body.groupintroduce) {
			res.status(200).json({
				ok: false,
				message: '课组简介不能为空！'
			});
			return;
		}
		//#endregion
		//编辑
		if (group_id) {
			//课组名称是否存在
			const d = await tbgroup().select('*').where({
				groupname: body.groupname
			});
			if (d.find((it) => { return it.group_id !== group_id; })) {
				res.status(200).json({
					ok: false,
					message: '课组名称不能重复！'
				});
				return;
			}
			await tbgroup().update(body).where({
				group_id
			});
		}
		//新增
		else {
			//课组名称是否存在
			const d = await tbgroup().first('*').where({
				groupname: body.groupname
			});
			if (d && d.groupname) {
				res.status(200).json({
					ok: false,
					message: '课组名称不能重复！'
				});
				return;
			}
			await tbgroup().insert({
				...body,
				group_id: Guid()
			});
		}

		res.status(200).json({ ok: true, message: '' });
	} catch (error) {
		logger.error(error);
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
